package com.mySampleApplication.client.CodeRuleAtter;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.mySampleApplication.client.codeRule.CodeRule;
import com.mySampleApplication.client.codeRule.CodeRuleWindow;
import com.mySampleApplication.client.codeRule.FdpzWindow;
import com.mySampleApplication.client.components.SDialog;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.SelectionAppearance;
import com.smartgwt.client.types.SelectionStyle;
import com.smartgwt.client.util.BooleanCallback;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.*;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.CellClickEvent;
import com.smartgwt.client.widgets.grid.events.CellClickHandler;
import com.smartgwt.client.widgets.grid.events.SelectionUpdatedEvent;
import com.smartgwt.client.widgets.grid.events.SelectionUpdatedHandler;
import com.smartgwt.client.widgets.layout.HLayout;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CodeRuleAtter {
    private static ListGrid plistGrid;


    public static ListGrid getPlistGrid() {
        return plistGrid;
    }

    public static void setPlistGrid(ListGrid plistGrid) {
        CodeRuleAtter.plistGrid = plistGrid;
    }
    // 自定义的 Formatter
    private static class CustomCellFormatter implements com.smartgwt.client.widgets.grid.CellFormatter {
        @Override
        public String format(Object value, ListGridRecord record, int rowNum, int colNum) {
            return Integer.toString(rowNum + 1); // 返回当前行的序号（行号）
        }
    }
    // 自定义的 Formatter
    private static class CustomCellFdlxFormatter implements com.smartgwt.client.widgets.grid.CellFormatter {
        @Override
        public String format(Object value, ListGridRecord record, int rowNum, int colNum) {

            return Dict.getFdlx().get(value.toString()); // 返回当前行的序号（行号）
        }
    }
    // 自定义的 Formatter
    private static class CustomCellFdmcFormatter implements com.smartgwt.client.widgets.grid.CellFormatter {
        @Override
        public String format(Object value, com.smartgwt.client.widgets.grid.ListGridRecord record, int rowNum, int colNum) {
            return "<span style='color: blue;cursor: pointer;'>" + value + "</span>"; // 使用 HTML 标签设置字体样式
        }
    }
    // 自定义的 Formatter
    private static class CustomCellBbFormatter implements com.smartgwt.client.widgets.grid.CellFormatter {
        @Override
        public String format(Object value, com.smartgwt.client.widgets.grid.ListGridRecord record, int rowNum, int colNum) {
            return "<span style='color: #fff;\n" +
                    "    background-color: #5de55da3;\n" +
                    "    \n" +
                    "    border-radius: 3px;\n" +
                    "    /* border: 1px silver solid; */\n" +
                    "    width: 30px;\n" +
                    "    padding: 0 20px;'>" + value + "</span>"; // 使用 HTML 标签设置字体样式
        }

    }

    public static Map<String,Object> getListGrid(ListGridRecord frecord) {
        Map<String,Object> map =new HashMap<>();
        // 创建一个列表网格控件
        ListGrid listGrid =getOp();

        ListGrid deleteListGrid = listGrid;
        ListGrid finalListGrid = listGrid;
        listGrid.setWidth100(); // 设置宽度为100%
        listGrid.setHeight100(); // 设置高度为100%
//        listGrid.setWidth(1024);
//        listGrid.setHeight(224);
        // 设置列表网格显示网格线
        listGrid.setShowAllRecords(false); // 显示所有记录
        // 开启分页功能
        listGrid.setDataPageSize(10); // 每页显示的数据条数
        //listGrid.setShowFilterEditor(true); // 显示过滤编辑器
//        listGrid.setSelectionType(SelectionStyle.MULTIPLE);//开启多选框
        //listGrid.setShowRowNumbers(true); // 显示行号
        //listGrid.setPaginationMode(PaginationMode.LOCAL); // 设置分页模式为本地分页
        //允许用户编辑行内容
        //listGrid.setCanEdit(true);
        //listGrid.setEditEvent(ListGridEditEvent.DOUBLECLICK); // 双击进行编辑
        listGrid.setModalEditing(true);
        listGrid.setVirtualScrolling(false);
        listGrid.setShowRecordComponents(true);
        listGrid.setShowRecordComponentsByCell(true);
        //listGrid.setCanRemoveRecords(true);


//        ListGridField selectedCountriesField = new ListGridField("name", "Selected");
//        selectedCountriesField.setWidth(70);
//        listGrid.setFields(selectedCountriesField);
//        listGrid.setSelectionType(SelectionStyle.SIMPLE);
//        listGrid.setSelectionAppearance(SelectionAppearance.CHECKBOX);

        // 定义列表网格的列
        ListGridField idField = new ListGridField("id", "序号");
        // 设置自定义的 Formatter
        idField.setCellFormatter(new CustomCellFormatter());
        idField.setWidth(50);
        ListGridField fdmcField = new ListGridField("fdmc", "分段名称");
        // 设置自定义的 Formatter
        fdmcField.setCellFormatter(new CustomCellFdmcFormatter());

        ListGridField fdsxField = new ListGridField("fdsx", "分段顺序");

        ListGridField fdlxField = new ListGridField("fdlx", "分段类型");
        fdlxField.setCellFormatter(new CustomCellFdlxFormatter());
        ListGridField bbField = new ListGridField("bb", "当前版本");
        bbField.setCellFormatter(new CustomCellBbFormatter());

        ListGridField create_timeField = new ListGridField("create_time", "创建时间");

        ListGridField actionField = new ListGridField("actionField", "操作");
        actionField.setWidth(230);

        if(!frecord.getAttribute("type").equals("bj")){
            listGrid.setFields(idField, fdmcField,fdlxField,fdsxField,bbField,create_timeField);
        }else{
            listGrid.setFields(idField, fdmcField,fdlxField,fdsxField,bbField,create_timeField,actionField);
        }

        // 创建按钮和事件处理
        Button addButton = new Button("Add");
        addButton.setTitle("新增");
        addButton.setIcon("[SKIN]/actions/add.png"); // 设置图标路径
        addButton.setShowRollOver(true);
        addButton.setShowDown(true);
        addButton.addClickHandler(event -> showAddDialog(finalListGrid,frecord));

        Button removeButton = new Button("Remove");
        removeButton.setIcon("[SKIN]/actions/remove.png"); // 设置图标路径
        removeButton.setTitle("删除");
//        removeButton.setAutoFit(true);
        // 禁用按钮
        removeButton.setDisabled(true);
        removeButton.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                ListGridRecord[] selectedRecord = finalListGrid.getSelectedRecords();
                if(selectedRecord != null && selectedRecord.length>0) {
                    int[] ids = new int[selectedRecord.length];
                    for (int i=0;i<selectedRecord.length;i++) {
                        ids[i]=Integer.parseInt(selectedRecord[i].getAttribute("id"));
                    }

                    SC.ask("是否删除该条数据?", new BooleanCallback() {
                        public void execute(Boolean value) {
                            if (value != null && value) {
                                CodeRuleAtterService.App.getInstance().setDelete(ids,new AsyncCallback<String>() {
                                    public void onSuccess(String result) {
                                        SC.say( "删除数据成功！");
                                        //list.addAll(result);
                                        Arrays.stream(selectedRecord).forEach(a->{
                                            finalListGrid.removeData(a);
                                            removeButton.setDisabled(true);
                                        });
                                    }

                                    public void onFailure(Throwable caught) {
                                        SC.warn("删除数据失败！");
                                    }
                                });
                            } else {

                            }
                        }
                    });

                } else {
                    SC.say("Select a record before performing this action");
                }
            }
        });

        HLayout buttonLayout = new HLayout();
        buttonLayout.setMembersMargin(10);
        buttonLayout.setAlign(Alignment.LEFT);
//        if(frecord.getAttribute("anNiu").equals("0")){
            if(frecord.getAttribute("type").equals("bj")){
                buttonLayout.addMembers(addButton);
            }
//        }else{
//            buttonLayout.addMembers(addButton);
//        }

        // 添加 CellClickHandler 处理单击事件
        listGrid.addCellClickHandler(new CellClickHandler() {
            @Override
            public void onCellClick(CellClickEvent event) {
                // 获取单击发生的行和列
                int rowNum = event.getRowNum();
                int colNum = event.getColNum();

                // 判断是否单击了指定的列
                if (colNum == listGrid.getFieldNum("fdmc")) {
                    // 获取单击处的数据
                   ListGridRecord record = listGrid.getRecord(rowNum);
//                    String value = record.getAttribute("fdmc");
//                    SC.say( "弹窗显示详情！"+record.getAttribute("fdmc"));
                    detRecord(record,listGrid,frecord);
                    // 执行其他操作...
                }
            }
        });


        //单选事件
        //listGrid.setData(listGrid.getSelectedRecord());
        listGrid.addSelectionUpdatedHandler(new SelectionUpdatedHandler() {
            public void onSelectionUpdated(SelectionUpdatedEvent event) {
                if(listGrid.getSelectedRecords().length>0){
                    removeButton.setDisabled(false);
                    if(listGrid.getSelectedRecords().length==1){
                        //EditButton.setDisabled(false);
                    }else {
                        //EditButton.setDisabled(true);
                    }
                }else {
                    removeButton.setDisabled(true);
                    //EditButton.setDisabled(true);
                }
                //SC.say(listGrid.getSelectedState());
            }
        });


        setPlistGrid(listGrid);
        map.put("listGrid",listGrid);
        map.put("finalListGrid",finalListGrid);
        map.put("buttonLayout",buttonLayout);
        return map;

    }

    private static ListGrid getOp(){
        return new ListGrid() {
            @Override
            protected Canvas createRecordComponent(final ListGridRecord record, Integer colNum) {

                String fieldName = this.getFieldName(colNum);
                if (fieldName.equals("actionField")) {
                    HLayout recordCanvas = new HLayout(3);
                    recordCanvas.setHeight(22);
                    recordCanvas.setWidth100();
                    recordCanvas.setAlign(Alignment.CENTER);
                    IButton chartImg = new IButton();
                    chartImg.setTitle("删除");
                    chartImg.setIcon("[SKIN]/actions/remove.png"); // 设置图标路径
                    chartImg.setWidth(60);
                    chartImg.addClickHandler(new ClickHandler() {
                        public void onClick(ClickEvent event) {
                            SC.ask("是否删除该条数据?", new BooleanCallback() {
                                public void execute(Boolean value) {
                                    if (value != null && value) {
                                        deleteRecord(record,event);
                                    }
                                }
                            });
                        }
                    });
                    recordCanvas.addMember(chartImg);

                    return recordCanvas;
                } else {
                    return null;
                }

            }
        };
    }


    private static void showAddDialog(ListGrid listGrid,ListGridRecord frecord) {
        Window dialog= CodeRuleAtterWindow.getShowWindow(false,900,350,"新增分段", null,listGrid,frecord);
        dialog.show();
    }


    private static void detRecord(final ListGridRecord record,ListGrid listGrid,ListGridRecord frecord) {
        Window dialog=CodeRuleAtterWindow.getShowWindow(true,900,350,"分段详情",record,listGrid,frecord);
        dialog.show();
        // 执行编辑操作
    }


    // 删除记录函数
    private static void deleteRecord(ListGridRecord record, ClickEvent event) {
        ListGrid listGrid = getPlistGrid();
        listGrid.removeData(record);
//        int[] ids = new int[0];
//        ids[0]=Integer.parseInt(record.getAttribute("id"));
//        CodeRuleAtterService.App.getInstance().setDelete(ids, new AsyncCallback<String>() {
//            public void onSuccess(String result) {
//
//                // 执行删除操作
//                SC.say( "删除数据成功！11");
//                //list.addAll(result);
//            }
//
//            public void onFailure(Throwable caught) {
//                SC.warn("删除数据失败！");
//            }
//        });

    }




}
